/*
 * @lc app=leetcode.cn id=10 lang=swift
 *
 * [10] 正则表达式匹配
 */

// @lc code=start
//
//  main.swift
//  test
//
//  Created by lanjing on 2021/7/29.
//

import Foundation
class Solution {
    func isMatch(_ s: String, _ p: String) -> Bool {
        return isMatch(source: Array(s), sourceIndex: 0, pattern: Array(p), patternIndex: 0)
    }

    func isMatch(source: Array<Character>, sourceIndex: Int,
                 pattern: Array<Character>, patternIndex: Int) -> Bool{
        if sourceIndex == source.count && patternIndex == pattern.count {
            return true
        }
        
        let sourceCharacter = source.safeIndex(index: sourceIndex)
        let patternCaracteer = pattern.safeIndex(index: patternIndex)
        if (sourceCharacter == patternCaracteer || patternCaracteer == ".")
            && sourceCharacter != nil{
            if pattern.isWildCharacterAtIndex(index: patternIndex + 1){
                    return isMatch(source: source, sourceIndex: sourceIndex + 1, pattern: pattern, patternIndex: patternIndex)
                        || isMatch(source: source, sourceIndex: sourceIndex, pattern: pattern, patternIndex: patternIndex + 2)

            }else{
                return isMatch(source: source, sourceIndex: sourceIndex + 1, pattern: pattern, patternIndex: patternIndex + 1)
            }
        }else{
            if pattern.isWildCharacterAtIndex(index: patternIndex + 1){
                return isMatch(source: source, sourceIndex: sourceIndex, pattern: pattern, patternIndex: patternIndex + 2)
            }else{
                return false
            }
        }
    }
    
}

extension Array{
    func safeIndex(index: Int) -> Element?{
        guard index >= 0 && index < self.count else {
            return nil
        }
        return self[index]
    }
}

extension Array where Element == Character{
    func isWildCharacterAtIndex(index: Int) -> Bool{
        let character = self.safeIndex(index: index)
        return character == "*"
    }
}



// @lc code=end

